﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace JavaReflectionLib
{
    class Communication
    {

        static Communication instance = null;
        static Socket client = null;

        public static Communication getInstance()
        {
            if (instance == null)
            {
                instance = new Communication();
            }
            return instance;
        }

        public Socket connect(int port)
        {
            IPEndPoint ip = null;
            try
            {
                ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }

            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                client.Connect(ip);
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.Message);
            }

            return client;
        }

        public static int sendMessage(int port, string title, string action)
        {
            string request = title + Const.AUTO_SPLIT + action;
            if (client == null)
                client = Communication.getInstance().connect(port);

            try
            {
                client.Send(Encoding.UTF8.GetBytes(request));
            }
            catch (SocketException e)
            {
                return -1;
            }

            client.Shutdown(SocketShutdown.Both);
            client.Close();
            client = null;

            return 1;
        }

        //public static int sendMessage(int port, string title, string action)
        //{
        //    string request = title + Const.AUTO_SPLIT + action;
        //    IPEndPoint ip = null;

        //    try
        //    {
        //        ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
        //    }
        //    catch (System.Exception e)
        //    {
        //        return -1;
        //    }

        //    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //    try
        //    {
        //        server.Connect(ip);
        //        server.Send(Encoding.UTF8.GetBytes(request));
        //    }
        //    catch (SocketException e)
        //    {
        //        return -1;
        //    }

        //    server.Shutdown(SocketShutdown.Both);
        //    server.Close();
        //    return 1;
        //}
    }
}
